<template>
  <div class="health-chart">
    <div ref="chartRef" class="chart-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts/core'
import { LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer
])

const props = defineProps({
  records: {
    type: Array,
    required: true
  },
  type: {
    type: Number,
    required: true
  }
})

const chartRef = ref(null)
let chart = null

const initChart = () => {
  if (!chartRef.value) return
  
  chart = echarts.init(chartRef.value)
  updateChart()
}

const updateChart = () => {
  if (!chart) return

  const dates = props.records.map(r => r.recordTime.substring(5, 10))
  let values = []
  
  if (props.type === 1) { // 体重
    values = props.records.map(r => parseFloat(r.recordValue))
  } else if (props.type === 2) { // 血压
    values = props.records.map(r => {
      const [systolic, diastolic] = r.recordValue.split('/')
      return [parseInt(systolic), parseInt(diastolic)]
    })
  }

  const option = {
    title: {
      text: props.type === 1 ? '体重趋势' : '血压趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates.reverse()
    },
    yAxis: props.type === 1 ? {
      type: 'value',
      name: '体重(kg)'
    } : [
      {
        type: 'value',
        name: '收缩压(mmHg)',
        min: 90,
        max: 200
      },
      {
        type: 'value',
        name: '舒张压(mmHg)',
        min: 60,
        max: 120
      }
    ],
    series: props.type === 1 ? [
      {
        name: '体重',
        type: 'line',
        data: values.reverse(),
        smooth: true
      }
    ] : [
      {
        name: '收缩压',
        type: 'line',
        data: values.map(v => v[0]).reverse(),
        smooth: true
      },
      {
        name: '舒张压',
        type: 'line',
        data: values.map(v => v[1]).reverse(),
        smooth: true,
        yAxisIndex: 1
      }
    ]
  }

  chart.setOption(option)
}

watch(() => props.records, updateChart, { deep: true })

onMounted(() => {
  initChart()
  window.addEventListener('resize', () => chart?.resize())
})

onUnmounted(() => {
  chart?.dispose()
  window.removeEventListener('resize', () => chart?.resize())
})
</script>

<style lang="scss" scoped>
.health-chart {
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
  margin: 12px;
  
  .chart-container {
    width: 100%;
    height: 300px;
  }
}
</style> 